package com.kylin.gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * 租户过滤器
 * @author wuhao
 * @version 1.0 - 2024/2/21
 */
@Component
public class TenantFilter extends AbstractGatewayFilterFactory<TenantFilter.Config> {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Autowired
    private DataSource dataSource;

    /** 获取租户ID的sql */
    private final String TENANT_ID_SQL = "select code from saas_tenant where domain = '%s'";

    public TenantFilter() {super(TenantFilter.Config.class);}

    /**
     * 配置示例
     * #验证码处理
     *   filters:
     *      - name: TenantFilter
     *        args:
     *          domainTenantIdSegment: 0  # 假设租户ID位于域名的第一段
     */
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            final String hostName = request.getLocalAddress().getHostName();
            System.out.println(hostName);

            System.out.println(request.getRemoteAddress().getHostString());

            System.out.println(request.getURI().getHost());
             String path = request.getURI().getPath();
            System.out.println(path + "|" + request.getURI().getRawPath());

            // 假设租户ID可以通过解析请求域名来获取
            String tenantId =  extractTenantIdFromDatabase(request.getURI().getHost());
            if (tenantId != null) {
                ServerHttpRequest mutatedRequest = request.mutate()
                        .header("X-Tenant-ID", tenantId)  // 将租户ID放入名为X-Tenant-ID的请求头
                        .build();
                return chain.filter(exchange.mutate().request(mutatedRequest).build());
            } else {
                // 如果未找到租户ID，可以根据实际情况处理，例如返回错误信息等
//                return exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            }
            return chain.filter(exchange);
        };
    }

    /**
     * 获取租户ID
     * @param null
     * @return  
     * @author wuhao
     * @version 1.0.0 - 2024/2/28
     */
    private String extractTenantIdFromDomain(String host, int segment) {
        // 在这里实现根据域名和配置的segment提取租户ID的逻辑
        // 这只是一个示例，实际逻辑需要根据你的具体业务进行编写
        return host.split("\\.")[segment];
    }

    /**
     * 获取租户ID
     * @param host 域名
     * @return
     * @author wuhao
     * @version 1.0.0 - 2024/2/28
     */
    private String extractTenantIdFromDatabase(String host) {
        // 在这里实现根据域名和配置的segment提取租户ID的逻辑
        List<Map<String, Object>> tenantList = jdbcTemplate.queryForList(String.format(TENANT_ID_SQL, host));
        if(!tenantList.isEmpty()) {
            return tenantList.get(0).get("code").toString();
        }
        return null;
    }


    public static class Config {
        // 如果租户ID是通过域名的某个部分来识别，你可以在这里配置
        private int domainTenantIdSegment;
    }
}
